package com.daisuxia.web.spider;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.daisuxia.constant.Constant;
import com.daisuxia.web.cache.CacheEntity;
import com.daisuxia.web.cache.CacheManager;
import com.daisuxia.web.cache.CacheTimerHandler;

/**
 * 网页解析规则、方案
 * 
 * @author simalin
 * 
 */
public class ParseSchemeService {

	public static final Logger loger = Logger
			.getLogger(ParseSchemeService.class);

	public static final ParseSchemeService instance = new ParseSchemeService();

	public List<SchemeRuleDto> schmesRuleList = new ArrayList<SchemeRuleDto>();

	public ParseSchemeService() {
	}

	public static ParseSchemeService getInstance() {
		return instance;
	}

	public List<SchemeRuleDto> getAllSchmesRuleList() {
		return schmesRuleList;
	}

	/**
	 * 获取、更新网页抓取方案及规则
	 */
	public void loadParseSchemes() {
		loger.info("********************************************");
		loger.info("*>-----获取、更新网页抓取方案及规则:列表页-----<*");
		loger.info("********************************************");

		CacheTimerHandler cache = CacheManager.getInstance()
				.getCacheTimerHandler();// 获取现有的规则

		Object obj = null;
		try {
			obj = cache.getCache(Constant.SCHEME);
		} catch (Exception d) {
			loger.info("------------cache-scheme--null-------");
		}

		if (null == obj) {
			loger.info("规则为：------>" + Constant.SCHEME);
			JSONObject jsonObject = JSONObject.fromObject(Constant.SCHEME);
			String status = jsonObject.getString("status");

			if (Constant.SCHEME_STATUS_ONE.equals(status)) {// status 1：有效 0：无效
				JSONArray schemeJSONArray = jsonObject.getJSONArray("schemes");
				if (null == schemeJSONArray || 0 == schemeJSONArray.size()) {
					loger
							.error("====!!!=====scheme result is emtpy====!!!=====");
					return;
				}

				List<SchemeRuleDto> schmeRuleList = new ArrayList<SchemeRuleDto>();
				List<RulesDto> rulesList = null;
				SchemeRuleDto schemeRuleDto = null;
				RulesDto rulesDto = null;
				JSONObject parseSchemeJSONObj = null;
				JSONObject parseRulesJSONObj = null;
				for (int i = 0; i < schemeJSONArray.size(); i++) {
					parseSchemeJSONObj = schemeJSONArray.getJSONObject(i);
					loger.info("--load--规则" + i + ":" + parseSchemeJSONObj);
					if (parseSchemeJSONObj.getString("type").equals(
							Constant.SCHEME_TYPE_LIST)) {// 1:列表 0:详情
						schemeRuleDto = loadParseSchemesByList(parseSchemeJSONObj);
					}
					if (parseSchemeJSONObj.getString("type").equals(
							Constant.SCHEME_TYPE_DETAIL)) {// 1:列表 0:详情
						schemeRuleDto = loadParseSchemesByDetail(parseSchemeJSONObj);
					}
					schmeRuleList.add(schemeRuleDto);
				}
				CacheEntity ce = new CacheEntity(Constant.SCHEME, schmeRuleList);
				cache.addCache(Constant.SCHEME, ce);
				schmesRuleList = schmeRuleList;
			} else {
				loger.error("====!!!=====scheme result is fail====!!!=====");
			}
		} else {
			List<SchemeRuleDto> srList = (List<SchemeRuleDto>) cache.getCache(
					Constant.SCHEME).getCacheKey(Constant.SCHEME);
			if (null != srList && 0 < srList.size()) {
				loger.info("--cache scheme is not null--");
			} else {
				loger
						.error("====!!!=====cache scheme is not null error====!!!=====");
			}
		}
	}

	/**
	 * 加载详情规则 封装dto
	 * 
	 * @param parseSchemeJSONObj
	 * @return
	 */
	private SchemeRuleDto loadParseSchemesByDetail(JSONObject parseSchemeJSONObj) {
		SchemeRuleDto schemeRuleDto = new SchemeRuleDto();
		schemeRuleDto.setStatus(parseSchemeJSONObj.getString("status"));
		schemeRuleDto.setType(parseSchemeJSONObj.getString("type"));
		schemeRuleDto.setSiteId(parseSchemeJSONObj.getString("siteid"));
		schemeRuleDto.setInfoKey(parseSchemeJSONObj.getString("infokey")
				.equals("") ? null : parseSchemeJSONObj.getString("infokey"));
		schemeRuleDto.setSelect(parseSchemeJSONObj.getString("select").equals(
				"") ? null : parseSchemeJSONObj.getString("select"));
		schemeRuleDto.setInfoValue(parseSchemeJSONObj.getString("infovalue")
				.equals("") ? null : parseSchemeJSONObj.getString("infovalue"));
		schemeRuleDto.setHostUrl(parseSchemeJSONObj.getString("hosturl"));
		schemeRuleDto.setPageUrl(parseSchemeJSONObj.getString("pageurl"));
		schemeRuleDto.setEnCode(parseSchemeJSONObj.getString("encode"));

		JSONArray rulesJSONArray = parseSchemeJSONObj.getJSONArray("rules");
		List<RulesDto> rulesList = new ArrayList<RulesDto>();
		JSONObject parseRulesJSONObj = null;
		RulesDto rulesDto = null;
		for (int j = 0; j < rulesJSONArray.size(); j++) {
			parseRulesJSONObj = rulesJSONArray.getJSONObject(j);
			rulesDto = new RulesDto();
			rulesDto.setParam(parseRulesJSONObj.getString("param"));
			rulesDto.setParamType(parseRulesJSONObj.getString("paramtype")
					.equals("") ? null : parseRulesJSONObj
					.getString("paramtype"));
			rulesDto.setDocSelect(parseRulesJSONObj.getString("docselect")
					.equals("") ? null : parseRulesJSONObj
					.getString("docselect"));
			rulesDto.setDocInfoKey(parseRulesJSONObj.getString("docinfokey")
					.equals("") ? null : parseRulesJSONObj
					.getString("docinfokey"));
			rulesDto.setDocInfoValue(parseRulesJSONObj
					.getString("docinfovalue").equals("") ? null
					: parseRulesJSONObj.getString("docinfovalue"));
			rulesDto
					.setSelect(parseRulesJSONObj.getString("select").equals("") ? null
							: parseRulesJSONObj.getString("select"));
			rulesDto.setInfoKey(parseRulesJSONObj.getString("infokey").equals(
					"") ? null : parseRulesJSONObj.getString("infokey"));
			rulesDto.setInfoValue(parseRulesJSONObj.getString("infovalue")
					.equals("") ? null : parseRulesJSONObj
					.getString("infovalue"));
			rulesList.add(rulesDto);
		}
		schemeRuleDto.setRulesList(rulesList);

		return schemeRuleDto;
	}

	/**
	 * 加载列表页规则 封装dto
	 * 
	 * @param parseSchemeJSONObj
	 * @return
	 */
	public SchemeRuleDto loadParseSchemesByList(JSONObject parseSchemeJSONObj) {
		SchemeRuleDto schemeRuleDto = new SchemeRuleDto();
		schemeRuleDto.setStatus(parseSchemeJSONObj.getString("status"));
		schemeRuleDto.setType(parseSchemeJSONObj.getString("type"));
		schemeRuleDto.setSiteId(parseSchemeJSONObj.getString("siteid"));
		schemeRuleDto.setInfoKey(parseSchemeJSONObj.getString("infokey"));
		schemeRuleDto.setSelect(parseSchemeJSONObj.getString("select").equals(
				"") ? null : parseSchemeJSONObj.getString("select"));
		schemeRuleDto.setInfoValue(parseSchemeJSONObj.getString("infovalue")
				.equals("") ? null : parseSchemeJSONObj.getString("infovalue"));
		schemeRuleDto.setHostUrl(parseSchemeJSONObj.getString("hosturl"));
		schemeRuleDto.setPageUrl(parseSchemeJSONObj.getString("pageurl"));
		schemeRuleDto.setEnCode(parseSchemeJSONObj.getString("encode"));

		JSONArray rulesJSONArray = parseSchemeJSONObj.getJSONArray("rules");
		List<RulesDto> rulesList = new ArrayList<RulesDto>();
		JSONObject parseRulesJSONObj = null;
		RulesDto rulesDto = null;
		for (int j = 0; j < rulesJSONArray.size(); j++) {
			parseRulesJSONObj = rulesJSONArray.getJSONObject(j);

			rulesDto = new RulesDto();
			rulesDto.setParam(parseRulesJSONObj.getString("param"));
			rulesDto
					.setSelect(parseRulesJSONObj.getString("select").equals("") ? null
							: parseRulesJSONObj.getString("select"));
			rulesDto.setInfoKey(parseRulesJSONObj.getString("infokey"));
			rulesDto.setInfoValue(parseRulesJSONObj.getString("infovalue")
					.equals("") ? null : parseRulesJSONObj
					.getString("infovalue"));
			rulesList.add(rulesDto);
		}
		schemeRuleDto.setRulesList(rulesList);
		return schemeRuleDto;
	}

	// public static void main(String[] args) {
	// getInstance().loadParseSchemes();
	// System.out.println(getInstance().getAllSchmesRuleList().size());
	// }
}
